/* Copyright (c) CERN
 * * Artistic License 2.0
 * */


import java.util.*;
import java.io.*;

/**
 * This program samples the input to get the required number of samples.
 * It also discards the first 1/10th of the input to erase the effect of starting the program.
 * Note this relies on the trace being long enough.
 *
 * Usage: java Sample nb input_file [output_file]
 *    - nb : number of samples.
 *    - input_file : file containing the initial samples.
 *    - output_file : generated file to be analyzed.
 *
 * @author Xavier Grehant
 */
class Sample {

/**
 * This method prints generated samples in a file.
 * @return
 * @param ground the generated samples
 * @param filename the name of the file to be written.
 */
   static void write(int ground[], String filename) throws IOException {
      FileWriter outfile = new FileWriter(new File(filename));
      for (int i = 0; i < ground.length; i++) {
         outfile.write(ground[i] + "\n");
      }
      outfile.close();
   }

/**
 * Main method.
 * This method handles the files and copies the appropriate samples.
 */
   public static void main(String args[]) {
        if (args.length > 1) {
            try {
                Random rand = new Random();
                // Open file
                FileInputStream fstream = new FileInputStream(args[1]);
                BufferedReader in = new BufferedReader(new InputStreamReader(fstream));
                Vector fromFile = new Vector();

                // Calculate useful stuff

                // number of samples
                String newValue;
                while ((newValue = in.readLine()) != null) {
                    Integer intValue = new Integer(newValue);
                    fromFile.add(intValue);
                }
                int number = new Integer(args[0]).intValue();
                int step = fromFile.size() * 9 / (number * 10);
                int[] fromVector = new int[(int) number];
                int index = fromFile.size() / 10;
                int randomized = 0;
                for (int i = 0; i < number; i++) {
                   fromVector[i] = ((Integer) fromFile.elementAt(index)).intValue();
                   randomized = 1 + rand.nextInt(2 * step - 1);
                   index += randomized;
                   if (index >= fromFile.size()) {
                      number = i;
                      break;
                   }
                }

                // Close file
                in.close();
                String outfilename;
                if (args.length > 2) outfilename = args[2];
                else outfilename = "sample.out";
                write(fromVector, outfilename);
            } catch (IOException e) {
               e.printStackTrace();
            }
        }
        else
            System.out.println("Invalid parameters");
    }
}
